package com.streaminggbs.controller;

import com.streaminggbs.common.base.ReturnBean;
import com.streaminggbs.entity.GbImport;
import com.streaminggbs.entity.LoginUser;
import com.streaminggbs.interfaces.GbInfoService;
import com.streaminggbs.common.utils.ExcelParseUtil;
import com.streaminggbs.common.utils.FileHandler;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * @Author LiLin
 * @Date 2020/10/19 10:44
 * @Description 国标管理
 */
@Api(tags = {"国标管理接口"})
@Slf4j
@RestController
@RequestMapping("gbInfo")
public class GbInfoController {

    @Autowired
    private GbInfoService gbInfoService;

    @ApiOperation(value = "国标导入", notes = "国标导入")
    @RequestMapping(value = "/import", method = RequestMethod.POST)
    public ReturnBean imports(HttpServletRequest request, HttpServletResponse response,
                                              @ApiParam(value = "文件名") @RequestParam(value = "fileName", required = true) String fileName,
                                              @ModelAttribute LoginUser loginUser
    ) {
        log.info("======国标导入接口==========，接受到的文件名：fileName=" + fileName);
        List<GbImport> list;
        try {
            list = ExcelParseUtil.GbExcelParse(FileHandler.BATH_PATH + fileName);
        }catch (Exception e){
            log.error("国标导入--解析表格报错", e);
            return new ReturnBean(-1,"解析表格异常");
        }
        //验证导入信息
        list = gbInfoService.validGbImport(list);
        //批量保存导入的信息
        try {
            gbInfoService.saveGbImport(list, loginUser.getSysUser());
            return new ReturnBean("导入成功");
        }catch (Exception e){
            log.error("国标导入--保存数据报错", e);
            return new ReturnBean(-1,"保存数据异常");
        }
    }
}
